import React from 'react';
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import * as teamAction from '../actions/team.action'
import { clearAtList, fetchAtList } from '../actions/home.action'
import { updateAvatar, fetchAddresses } from '../actions/app.action'
import { fetchRole, delStaff, createDocument, updateOnboardingFlowStatus } from '../actions/onboarding.hr.action'
import { fileUpload } from '../actions/file.action'
import * as userAction from '../actions/user.action'
import {ROOT_TEAM} from '../constants'
import style from './style.role'
import { fetchOrg } from '../actions/system.action'


import { Table, Button, IconFont, Link,Modal, TitleBar, Checkbox, info, success,  } from '../ui-components'
import cx from 'classnames'
import util from '../util'
import moment from 'moment'
import userStatus from '../constants/userStatus'
import { map as tableMap } from '../ui-components/table'
import { u } from '../actions/util'

function ToolTip(props){
    return(
        <a href="javascript:void(0);" className={style["toolTip"]}>
            <span className={style["toolTip-content"]}>{props.title}</span>
            {
                props.children
            }
        </a>
    );
}

@connect(({team,app,user}) => ({ team,app,user }))
class MyTeam extends React.Component {

  state = {
    isFetchingTeamUsers: false,
    teamId: null,
    roles: [],
  }

  pageSize = 30
  pageNumber = 1

  handleSearch(e) {
    const { value } = e.target
    const { teamId } = this.props.location.query

    util.throttle(() => {
      this.props.router.push(`/roleSettings?${util.body({teamId, keyword: value})}`)
    })
  }

  componentWillReceiveProps(props) {
    const { keyword } = props.location.query
    const { keyword: prevKeyword } = this.props.location.query
    if(!this.state.teamId){
      const {
        org = {}
      } = props.app;
      if(org.teamVO) {
        const id = org.teamVO.teamId;
        this.setState({
          teamId: id,
        });
        this.fetchTeamUsers(props, id);
      }
    }
    
    // 切换关键字
    if (keyword != prevKeyword) {
      this.fetchTeamUsers(props)
    }

    if (props.team.isFetchingTeamUsers !== this.props.team.isFetchingTeamUsers) {
      this.setState({
        isFetchingTeamUsers: false
      })
    }

    if (props.user.roles.length && !this.props.user.roles.length) {
      this.setState({
        roles: props.user.roles
      })
    }

  }


  componentDidMount() {

    this.setState({
      isFetchingTeamUsers: true,
    })


    this.fetchTeamUsers()
    this.props.fetchOrg();
  }


  fetchTeamUsers(props, teamId) {
    props = props || this.props
    let { keyword, pageNumber } = props.location.query

    if (pageNumber == null) pageNumber = this.pageNumber
    this.props.fetchTeamUsers({
      teamId: teamId || this.state.teamId || this.props.zero,
      keyword,
      pageNumber,
      pageSize: this.pageSize
    })
  }

  



  handlePageChage(_pageNumber) {
    const { pageNumber, ...others } = this.props.location.query
    this.props.router.push(`/roleSettings?pageNumber=${_pageNumber}&${util.body(others)}`)
  }

  renderTeamUsers() {
    //权限控制根据roleList 配置
    let managable = 0;
    if(this.props.app){
      const {roleNameList = []} = this.props.app.profile || {}; 
      if(~roleNameList.indexOf('HR')) {
        managable = 1;
      }else if(~roleNameList.indexOf('orgAdmin')) {
        managable = 2;
      }
    }
    const { totalRecordNum, UserProfiles: list } = this.props.team.teamUser
    const config = {
      pagin: typeof totalRecordNum === 'number' && {
        pageSize: this.pageSize,
        pageNumber: this.props.location.query.pageNumber || this.pageNumber,
        totalNumber: totalRecordNum,
        onChange: ::this.handlePageChage,
        fetch: ::this.fetchTeamUsers
      },
      model: {
        fullName: '姓名',
        userEmploymentVO: '状态',
        jobTitleName: '职位',
        enrollDate: '入职时间',
        others: '操作'
      },
      config: {
        others: '.5',
      },
      map: {
        fullName: (v, user) => { 
          return <div
              style={{
                display: 'flex',
                alignItems: 'center'
              }}
            >
                {
                  user.avatarUrl?
                  <i style={{ borderRadius: '50%', width: '38px', height: '38px', backgroundImage: `url(${user.avatarUrl})`,display: 'block', ...util.crop(user.avatarUrl, 38) }}/>
                  : <IconFont value="avatar" style={{ border: '1px solid #b9cee6', backgroundColor: '#eaf2fb', color: '#b9cee6', overflow: 'hidden', borderRadius: '50%', fontSize: '28px', width: '38px', 'height': '38px' }}/>
                }
              <span><ToolTip title={user.emailAddress}>{ v }</ToolTip></span>
            </div>
        },
        userEmploymentVO: value => {
          return <span className={cx({
            [style.userStatus]: true,
            [style.leave]: value == 4
          })}
          >{ userStatus(value) || ''}</span>
        },
        enrollDate: value => value && moment(value).format('YYYY.MM.DD'),
        others: (value, item) => {
          return (
            <span >
              <Link className={style['link']} onClick={() => this.requestConfigAuth(item)} label={'配置权限'}/>
            </span>
          )
        } 
      }
    }
    return (
      <Table
        loading={this.state.isFetchingTeamUsers}
        className={style.teamUsers}
        data={list}
        { ...config }
      />
    )
  }
  requestConfigAuth(user) {
      this.props.fetchRole(user.userId)
      this.setState({
        configAuthUser: user,
        configAuth: true,
        roles: []
      })
    }
  cancelConfigAuth() {
    this.setState({
      configAuth: false,
      configAuthUser: null
    })
    this.props.resetUser()
  }
  toggleRoles(id) {
    this.setState({
      roles: this.state.roles.map((r, i) => {
        if(r.roleId == id) {
          return {
            ...r,
            flag: !r.flag
          }
        }
        return r
      })
    })
  }
  updateAuth() {
    info('更新中...')
    const { configAuthUser, roles } = this.state;
    this.props.updateUserRole(roles.filter(r => r.flag).map(r => ({ idValue: r.roleId })), configAuthUser.userId, () => {
      success('更新成功!')
    })
    this.cancelConfigAuth()
  }
  render() {
    const { ancestorTeams=[], childrenTeams=[] } = this.props.team.teamAncestorChildren
    return (
      <div className={style['team']}>
        <div>
          <div >
            <input 
              onChange={::this.handleSearch}
              className={style['input']}
              placeholder="输入姓名/姓名拼音..."/>
          </div>
        </div>
        {
          this.renderTeamUsers()
        }
         <Modal
          active={this.state.configAuth}
          onRequestClose={::this.cancelConfigAuth}
          actions={[
            'cancel',
            ::this.updateAuth
          ]}
          title={`给${(this.state.configAuthUser || {}).fullName || ''}配置权限`}
        >
          <div className={style['auth-check-list']}>
            {
              this.state.roles.map((v, i) => (
                <Checkbox 
                  className={style['auth-check']}
                  disabled={!v.editable}
                  active={v.flag}
                  onClick={() => {
                    if (v.editable) {
                      this.toggleRoles(v.roleId)
                    }
                  }}
                  key={i}
                  label={v.roleDesc}
                />
              ))
            }
          </div>
        </Modal>
      </div>
    )
  }
}



@connect(({app}) => ({app}), dispatch => ({actions: bindActionCreators({...teamAction, ...userAction, clearAtList, fetchAtList, updateAvatar, fetchAddresses, createDocument, fileUpload, updateOnboardingFlowStatus, delStaff, fetchRole, fetchOrg }, dispatch)}))
class RoleSettings extends React.Component {
    constructor(props) {
        super(props);
        this.displayName = 'RoleSettings';
    }
    static contextTypes = {
      router: React.PropTypes.object
    }
    render() {
        return <MyTeam zero={ROOT_TEAM} {...this.context} location={this.props.location} {...this.props.actions}/>;
    }
}

export default RoleSettings;
